package com.yfbao.horizon.schedule.tk.aspect;

import com.yfbao.horizon.schedule.tk.annotation.CompositeCacheable;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
@Order(1000)
public class CompositeCacheAspect extends AbstractMetricMethodAspect {

    @Pointcut("@annotation(com.yfbao.horizon.schedule.tk.annotation.CompositeCacheable)")
    public void checkCompositeCache() {
    }

    /**
     * 环绕处理
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "checkCompositeCache()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        //得到注解参数列表,组装缓存key
        CompositeCacheable methodAnnotation = getMethodAnnotation(joinPoint, CompositeCacheable.class);
        if(methodAnnotation ==null){
            //找不到对应注解，直接跳过处理
            return joinPoint.proceed();
        }
//        methodAnnotation.first();
        // 调用原始的 @Cacheable 注解的逻辑
//        Cacheable cacheable = joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName(), joinPoint.getArgs().getClass())
//                .getAnnotation(Cacheable.class);
//        // 如果 @Cacheable 注解存在，则调用其逻辑
//        if (cacheable != null) {
//            // 执行原有的 @Cacheable 注解逻辑
//        } else {
//            // 如果 @Cacheable 注解不存在，可能是在测试环境中，或者其他情况
//            // 可以根据实际需求进行处理
//            return joinPoint.proceed();
//        }

        String[] strings = methodAnnotation.cacheNames();
        if(strings ==null || strings.length==0){
            throw new RuntimeException("cacheName must be not null or empty!");
        }
        String key = methodAnnotation.key();
        Object[] args = joinPoint.getArgs();
        if(key==null){
            key="";
            for (Object arg : args) {
                key=key+"_"+arg.toString();
            }
        }
        //得到注解所在函数的入参


        Class<?> aClass = joinPoint.getTarget().getClass();
        //先校验方法上的注解

        //执行方法
        Object proceed = joinPoint.proceed();
        //todo:执行完方法后写缓存

        return proceed;
    }
}
